$(document).ready(function() {
    var user_info = {};
    var user_id = 0;
    var pollingInterval = 5000;
    var data_type = 'goods';
    let lastScanTime = 0; // 上次扫码时间
    const scanInterval = 20000; // 20秒限制
    let barcode = ''; // 用于存储扫码数据
    var currentkey = sessionStorage.getItem('currentkey');
    if (currentkey) {
        var current_key = JSON.parse(currentkey);
        data_type = current_key['datatype'];
    }

    var customerinfo = sessionStorage.getItem('customer');
            
    if(customerinfo && customerinfo.length != 0){
        user_info = JSON.parse(customerinfo);
        user_id = user_info.id;
    }else{
        window.location = '/cashdesk';
    }

    $(".active-btn-item").removeClass('active-btn-item');
    $(".btn-item[data-datatype='"+data_type+"']").addClass('active-btn-item');

    //时间选择器
    laydate.render({
      elem: '#supplementtime'
      ,type: 'datetime'
      ,max: new Date().getTime()
    });

    //初始化数据
    initdata(data_type);
    
    //返回开单
    $(document).on("click", ".go-back-div", function () {
        window.location = '/cashdesk';
    });
    
    //关闭开单
    $(document).on("click", ".close_order_btn", function () {
        clearSession(data_type);
        window.location = '/cashdesk';
    });

    //关闭
    $(document).on("click", ".close-item", function () {
        let item_id = $(this).parent(".resultant-item").data('id');
        let item_ptype = $(this).parent(".resultant-item").data('ptype');
        $(this).parent(".resultant-item").remove();
        
        if (item_ptype == 2) {
            $('.payment-item[data-ptype=2]').show();
            $('.pay-order-div').hide();
        }else{
            $('.payment-item[data-id="'+item_id+'"]').show();
        }
        updatePaymentAmount();
    });

    //选择支付方式 10 二维码支付 / 12 扫码支付
    $(document).on("click", ".payment-item", function () {
        let item_id = $(this).data('id');
        let item_ptype = $(this).data('ptype');
        let item_img = $(this).find('.payment-img').attr('src');
        let item_name = $(this).find('.payment-name').text();
        let actual_amount = $('.actual_amount').data('amount');

        if (item_id == 10) {
            $('.pay-order-div').show();
            $('.qrcode-pay-item').show();
            $('.scan-pay-item').hide();
        }else if(item_id == 12){
            $('.pay-order-div').show();
            $('.scan-pay-item').show();
            $('.qrcode-pay-item').hide();
        }

        let add_html = '';
        add_html += '<div class="resultant-item" data-id="'+item_id+'" data-ptype="'+item_ptype+'">';
        add_html += '<img class="resultant-img" src="'+item_img+'">';
        add_html += '<span class="method-name">'+item_name+'</span>';
        if ($('.resultant-item').length == 0) {
            add_html += '<input type="number" step="0.01" min="0.00" class="pay_amount" placeholder="0.00" value="'+actual_amount+'" />';
        }else{
            add_html += '<input type="number" step="0.01" min="0.00" class="pay_amount" placeholder="0.00" value="0.00" />';
        }
        add_html += '<a href="javascript:void(0);" class="link get-all-amount">全额</a>';
        add_html += '<a href="javascript:void(0);" class="link get-difference-amount">差额</a>';
        add_html += '<span class="close close-item">×</span>';
        add_html += '</div>';
        $('.payment-resultant').append(add_html);
        if (item_ptype == 2) {
            $('.payment-item[data-ptype=2]').hide();
        }else{
            $(this).hide();
        }
        $('.actual_amount').text(0);
        updatePaymentAmount();
    });

    //获取全额
    $(document).on("click", ".get-all-amount", function () {
        let actual_amount = $('.actual_amount').data('amount');
        let pay_item_obj = $('.pay_amount');
        pay_item_obj.each(function(index, element) {
            $(this).val('0.00');
        });
        $(this).prev('input').val(actual_amount);
        updatePaymentAmount();
    });

    //获取差额
    $(document).on("click", ".get-difference-amount", function () {
        let actual_amount = $('.actual_amount').data('amount');
        let pay_item_obj = $('.pay_amount');
        let total_amount = 0;
        pay_item_obj.each(function(index, element) {
            const $this = $(element);
            let amount = parseFloat($this.val()) || 0;
            let curamount = amount.toFixed(2);
            if (amount > 0) {
                total_amount += amount;
            }
        });

        if (total_amount > actual_amount) {
            $(this).val(0);
            layer.open({
                type: 1,
                title:'提示',
                area: ['400px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">超出总金额，请输入正确的收款金额！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    updatePaymentAmount();
                    // index是弹窗的索引，layero是弹窗的DOM对象
                    layer.close(index); // 关闭弹窗
                }
            });
            return false;
        }else if(total_amount < actual_amount){
            let difference_amount = parseFloat(actual_amount - total_amount).toFixed(2);
            $(this).prev().prev('input').val(difference_amount);
        }
        updatePaymentAmount();
    });

    //设置金额
    $(document).on("input", ".pay_amount", function () {
        const value = $(this).val();
        let actual_amount = $('.actual_amount').data('amount');
        let total_amount = 0;
        const isNum = !isNaN(parseFloat(value)) && parseFloat(value) === parseFloat(value); // 验证数字

        if (!isNum) {
            $(this).val(0);
            layer.open({
                type: 1,
                title:'提示',
                area: ['500px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">请输入正确的收款金额！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    updatePaymentAmount();
                    // index是弹窗的索引，layero是弹窗的DOM对象
                    layer.close(index); // 关闭弹窗
                }
            });
            return false;
        }

        let cur_amount = parseFloat(value).toFixed(2);
        let pay_item_obj = $('.pay_amount');
        pay_item_obj.each(function(index, element) {
            const $this = $(element);
            let amount = parseFloat($this.val()) || 0;
            let curamount = amount.toFixed(2);
            if (amount > 0) {
                total_amount += amount;
            }
        });

        if (total_amount > actual_amount) {
            $(this).val(0);
            layer.open({
                type: 1,
                title:'提示',
                area: ['400px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">超出总金额，请输入正确的收款金额！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    updatePaymentAmount();
                    // index是弹窗的索引，layero是弹窗的DOM对象
                    layer.close(index); // 关闭弹窗
                }
            });
            return false;
        }
        updatePaymentAmount();
    });

    //选择优惠券
    $(document).on("click", ".coupon_list_item", function () {
        var countkey = 'goodsordercount_'+user_id;
        if (data_type == "cards") {
            countkey = 'cardsordercount_'+user_id;
        }
        var ordersCount = sessionStorage.getItem(countkey);

        if(!$(this).hasClass('coupon_list_item_active')){
            $(this).addClass('coupon_list_item_active');
            $(".coupon_list_item_active").not(this).removeClass('coupon_list_item_active');
            var coupon_id = $(this).data('couponid');
            var coupon_price = parseFloat($(this).data('couponprice')).toFixed(2);
            var coupon_type = $(this).data('coupontype');
            var coupon_discount = parseFloat($(this).data('coupondiscount')).toFixed(2);
            var coupon_limit = $(this).data('couponlimit');

            if (ordersCount) {
                var ordersCountInfo = JSON.parse(ordersCount);
                ordersCountInfo['coupon'] = {};
                if (coupon_type == 'reduction') {
                    if (ordersCount >= coupon_limit) {
                        ordersCountInfo['coupon'] = {'coupon_id':coupon_id,'coupon_price':coupon_price,'coupon_type':coupon_type,'coupon_limit':coupon_limit};
                        ordersCountInfo['discount'] = coupon_price;
                    }
                    
                }else if (coupon_type == 'discount') {
                    ordersCountInfo['coupon'] = {'coupon_id':coupon_id,'coupon_discount':coupon_discount,'coupon_type':coupon_type};
                    ordersCountInfo['discount'] = parseFloat(ordersCountInfo['originalfee'] * (1 - coupon_discount)).toFixed(2);
                }
                //更新订单信息
                var serializedArray = JSON.stringify(ordersCountInfo);
                sessionStorage.setItem(countkey, serializedArray);
            }
        }else{
            $(".coupon_list_item_active").removeClass('coupon_list_item_active');
            if (ordersCount) {
                var ordersCountInfo = JSON.parse(ordersCount);
                ordersCountInfo['coupon'] = {};
                ordersCountInfo['discount'] = 0;
                //更新订单信息
                var serializedArray = JSON.stringify(ordersCountInfo);
                sessionStorage.setItem(countkey, serializedArray);
            }
        }
        $(".pay-order-div").hide();
        sessionStorage.removeItem(data_type+'orderpay_'+user_id);
        initdata(data_type);
        return false;
    });

    //选择充值卡项
    $(document).on("click", ".card-coupon-item-div", function () {
        var countkey = 'goodsordercount_'+user_id;
        if (data_type == "cards") {
            countkey = 'cardsordercount_'+user_id;
        }
        var cur_index = $(".card-coupon-item-div").index(this);
        var ordersCount = sessionStorage.getItem(countkey);
        if(!$(this).hasClass('coupon_active')){
            $(".card-coupon-item-div").removeClass('coupon_active');
            $(this).addClass('coupon_active');
            var card_id = $(this).data('cardid');
            var card_price = parseFloat($(this).data('cardprice')).toFixed(2);

            if (ordersCount) {
                var ordersCountInfo = JSON.parse(ordersCount);
                ordersCountInfo['cardcoupon'] = {};
                ordersCountInfo['cardcoupon'] = {'card_id':card_id,'card_price':card_price};
                ordersCountInfo['carddiscount'] = card_price;
                $(".card_discount").text('￥'+card_price);
                //更新订单信息
                var serializedArray = JSON.stringify(ordersCountInfo);
                sessionStorage.setItem(countkey, serializedArray);
            }
        }else{
            $(this).removeClass('coupon_active');
            if (ordersCount) {
                var ordersCountInfo = JSON.parse(ordersCount);
                ordersCountInfo['cardcoupon'] = {};
                ordersCountInfo['carddiscount'] = 0;
                //更新订单信息
                var serializedArray = JSON.stringify(ordersCountInfo);
                sessionStorage.setItem(countkey, serializedArray);
            }
        }
        $(".pay-order-div").hide();
        sessionStorage.removeItem(data_type+'orderpay_'+user_id);
        initdata(data_type);
        return false;
    });

    //结账
    $(document).on("click", ".pay_item_btn", function () {
        var remarks = $(".remarks").val();
        var issupplement = $('input[name="issupplement"]:checked').val();
        var supplementtime = $('#supplementtime').val();
        if (issupplement == 1 && supplementtime == '') {
            layer.open({
                type: 1,
                title:'提示',
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">请选择记账时间</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    // 点击确定按钮后的回调函数
                    // index是弹窗的索引，layero是弹窗的DOM对象
                    layer.close(index); // 关闭弹窗
                    $('.pay_item_btn').attr('disabled',false);
                }
            });
            return false;
        }

        var customer = sessionStorage.getItem('customer');
        if(customer && customer.length != 0){
            var user_info = JSON.parse(customer);
            var user_id = user_info.id;
            var countkey = 'goodsordercount_'+user_id;
            var orderkey = 'goodsorder_'+user_id;
            var paykey = 'goodsorderpay_'+user_id;
            if (data_type == "cards") {
                countkey = 'cardsordercount_'+user_id;
                orderkey = 'cardsorder_'+user_id;
                paykey = 'cardsorderpay_'+user_id;
            }

            //订单统计
            var ordercount = sessionStorage.getItem(countkey);
            //订单详情
            var orderinfo = sessionStorage.getItem(orderkey);
            //扫码结果
            var scan_result = '';
            //支付信息
            var payinfo = sessionStorage.getItem(paykey);
            var pay_info = JSON.parse(payinfo);
            var pay_way_id = 0;
            var pay_total_amount = 0;
            if (payinfo && pay_info.length > 0){
                var shouldBreak = false;
                try {
                    $.each(pay_info, function (index, item) {
                        if (item.id == 10 || item.id == 12) {
                            pay_way_id = item.id;
                        }
                        let amount = parseFloat(item.amount) || 0;
                        pay_total_amount += amount;
                        if(item.type == 2 && item.amount == 0){
                            layer.open({
                                type: 1,
                                title:'提示',
                                area: ['280px', '180px'],
                                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">在线支付金额不能为0！</p>',
                                btn: ['确定'], // 弹窗按钮
                                btnAlign:"c",
                                yes: function(index, layero){
                                    // 点击确定按钮后的回调函数
                                    // index是弹窗的索引，layero是弹窗的DOM对象
                                    layer.close(index); // 关闭弹窗
                                    $('.pay_item_btn').attr('disabled',false);
                                }
                            });
                            shouldBreak = true; // 设置标志以终止循环
                            throw new Error('在线支付金额不能为0！');
                            // return false; // 返回false以停止$.each()的迭代
                        }

                        if(item.id == 12){
                            var scanres = sessionStorage.getItem('scanres');
                            if(scanres && scanres.length != 0){
                                scan_res = JSON.parse(scanres);
                                scan_result = scan_res['code'];
                            }else{
                                layer.open({
                                    type: 1,
                                    title:'提示',
                                    area: ['280px', '180px'],
                                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">扫码失败，请确认后重试！</p>',
                                    btn: ['确定'], // 弹窗按钮
                                    btnAlign:"c",
                                    yes: function(index, layero){
                                        // 点击确定按钮后的回调函数
                                        // index是弹窗的索引，layero是弹窗的DOM对象
                                        layer.close(index); // 关闭弹窗
                                        $('.pay_item_btn').attr('disabled',false);
                                    }
                                });
                                shouldBreak = true; // 设置标志以终止循环
                                throw new Error('扫码失败，请确认后重试！');
                                // return false; // 返回false以停止$.each()的迭代
                            }
                        }
                    });
                } catch (e) {
                  console.error(e.message);
                  return false;
                }
            }else{
                layer.open({
                    type: 1,
                    title:'提示',
                    area: ['280px', '180px'],
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">请选择支付方式！</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        // 点击确定按钮后的回调函数
                        // index是弹窗的索引，layero是弹窗的DOM对象
                        layer.close(index); // 关闭弹窗
                        $('.pay_item_btn').attr('disabled',false);
                    }
                });
                return false;
            }

            if (orderinfo) {
                $('.pay_item_btn').attr('disabled',true);
                $('.go-back-div').css("display","none");
                
                var count_info = JSON.parse(ordercount);
                count_info['remarks'] = remarks;
                count_info['issupplement'] = issupplement;
                count_info['supplementtime'] = supplementtime;

                var actual_amount = 0;
                if (orderinfo['modifyfee'] != 0) {
                    actual_amount = count_info['modifyfee'] - count_info['discount'] - count_info['discountfee'] - count_info['carddiscount'] - count_info['vipdiscount'];
                }else{
                    actual_amount = count_info['totalfee'] - count_info['discount'] - count_info['discountfee'] - count_info['carddiscount'] - count_info['vipdiscount'];
                }
                if (actual_amount < 0 ) {
                    actual_amount = 0;
                }
                actual_amount = parseFloat(actual_amount).toFixed(2);
                pay_total_amount = parseFloat(pay_total_amount).toFixed(2);

                if (pay_total_amount != actual_amount) {
                    layer.open({
                        type: 1,
                        title:'提示',
                        area: ['500px', '180px'],
                        content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">订单待支付金额与支付金额不一致，请确认后重试!</p>',
                        btn: ['确定'], // 弹窗按钮
                        btnAlign:"c",
                        yes: function(index, layero){
                            // 点击确定按钮后的回调函数
                            // index是弹窗的索引，layero是弹窗的DOM对象
                            layer.close(index); // 关闭弹窗
                            $('.pay_item_btn').attr('disabled',false);
                        }
                    });
                    return false;
                }

                //更新订单信息
                var serializedArray = JSON.stringify(count_info);
                sessionStorage.setItem(countkey, serializedArray);
                var order_info = JSON.parse(orderinfo);
                $.ajax({
                    type: 'POST',
                    url: '/cashdesk/index/createorder',
                    dataType: "json",
                    data: {ordercount:count_info,orderinfo:order_info,payinfo:pay_info,userinfo:user_info,datatype:data_type,scanresult:scan_result},
                    success: function (ret) {
                        if (ret.code != 1) {
                            layer.open({
                                type: 1,
                                title:'提示',
                                area: ['280px', '180px'],
                                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                                btn: ['确定'], // 弹窗按钮
                                btnAlign:"c",
                                yes: function(index, layero){
                                    // 点击确定按钮后的回调函数
                                    // index是弹窗的索引，layero是弹窗的DOM对象
                                    layer.close(index); // 关闭弹窗
                                    $('.pay_item_btn').attr('disabled',false);
                                }
                            });
                            return false;
                        }else{
                            if (pay_way_id != 10 && pay_way_id != 12) {
                                layer.confirm('下单成功，确定要继续开单吗？', {
                                    title: '确认提示',
                                    btn: ['继续', '取消']
                                }, function (index) {
                                    layer.close(index);
                                    clearSession(data_type,0);
                                    window.location = '/cashdesk';
                                }, function (index) {
                                    layer.close(index); // 关闭弹窗
                                    clearSession(data_type);
                                    window.location = '/cashdesk';
                                });
                            }else{
                                $('.pay_item_btn').attr('disabled',true);
                                if(pay_way_id != 12){
                                    if (ret.data.qrcode_url && ret.data.qrcode_url.length > 0) {
                                        var qrcode_params = {
                                            text: ret.data.qrcode_url,
                                            label: '客户手机扫此收款码',
                                            logo: 0,
                                            labelalignment: 'center',
                                            foreground: '#000000',
                                            background: '#ffffff',
                                            size: 50,
                                            padding: 10,
                                            logosize: 50,
                                            labelfontsize: 14,
                                            errorcorrection: 'medium',
                                        };
                                        //生成支付二维码
                                        createQrcode(qrcode_params);
                                        var ordercount = sessionStorage.getItem(countkey);
                                        var count_info = JSON.parse(ordercount);
                                        count_info['qrcode_img'] = $(".pay_qrcode").attr("src");
                                        count_info['order_id'] = ret.data.order_id;
                                        var serializedArray = JSON.stringify(count_info);
                                        sessionStorage.setItem(countkey, serializedArray);
                                    }
                                }
                                
                                // 使用闭包来传递参数
                                var poll = function(order_no) {
                                    $.ajax({
                                        url: '/cashdesk/index/checkorderstatus',
                                        type: 'POST',
                                        data: { order_no: order_no },  // 传递参数
                                        success: function(ret) {
                                            // 检查是否需要停止轮询
                                            if (ret.code == 1) {
                                                console.log('Polling stopped.');
                                                clearInterval(intervalId);  // 停止轮询

                                                layer.confirm('下单成功，确定要继续开单吗？', {
                                                    title: '确认提示',
                                                    btn: ['继续', '取消']
                                                }, function (index) {
                                                    layer.close(index);
                                                    clearSession(data_type,0);
                                                    window.location = '/cashdesk';
                                                }, function (index) {
                                                    layer.close(index); // 关闭弹窗
                                                    clearSession(data_type);
                                                    window.location = '/cashdesk';
                                                });
                                            } else {
                                                console.log('Polling in progress...');
                                            }
                                        },
                                        error: function() {
                                            console.log('Error in polling.');
                                        }
                                    });
                                };

                                var intervalId = setInterval(function() {
                                    poll(ret.data.order_no);  // 传递参数值
                                }, pollingInterval);
                                
                                return false;
                            }
                            
                        }
                    },
                    error: function (ret) {
                        layer.open({
                            type: 1, 
                            area: ['280px', '180px'],
                            title:'提示',
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                layer.close(index); // 关闭弹窗
                                $('.pay_item_btn').attr('disabled',false);
                            }
                        });
                        return false;
                    }
                });
            }
            
        }
    });

    //扫码枪支付
    $(document).on("click", ".scan_pay_title", function () {
        // 设置隐藏输入框获取焦点
        $('#scan-input').focus();

        $(document).keypress(function (e) {
            const currentTime = Date.now();

            // 如果在10秒内已经处理过扫码数据，则忽略
            if (currentTime - lastScanTime < scanInterval) {
                return;
            }

            // 获取按键对应的字符
            const char = String.fromCharCode(e.which);

            // 如果是回车键，则表示扫码结束
            if (e.which === 13) {
                if (barcode) {
                    // 处理扫码数据
                    $('#scan-input').val(`${barcode}`);
                    $('#scan-input').blur();
                    var scanres = sessionStorage.getItem('scanres');
                    var scan_result = {};

                    //保存扫码数据
                    scan_result['code'] = barcode;
                    //更新扫码数据
                    var serializedArray = JSON.stringify(scan_result);
                    sessionStorage.setItem('scanres', serializedArray);
                    console.log(`扫码结果：${barcode}`);

                    // 更新时间戳并清空扫码数据
                    lastScanTime = currentTime;
                    barcode = '';
                }
            } else {
                // 将扫码数据拼接起来
                barcode += char;
            }
        });
    });
    
    //序列化参数
    function objectToQueryString(obj){
        return Object.entries(obj).map(([key, value]) => `${key}=${value}`).join('&');
    }

    //初始化数据
    function initdata(data_type){
        //默认加载买家信息
        var customerinfo = sessionStorage.getItem('customer');
        var serve_html = "";
        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;
            var countkey = "goodsordercount_"+user_info.id;
            var paykey = "goodsorderpay_"+user_info.id;
            if (data_type == 'cards') {
                countkey = "cardsordercount_"+user_info.id;
                paykey = "cardsorderpay_"+user_info.id;
            }
            var ordersCount = sessionStorage.getItem(countkey);
            var orderinfo = JSON.parse(ordersCount);

            var payCount = sessionStorage.getItem(paykey);
            var payinfo = JSON.parse(payCount);
            var payways = [];

            //加载客户信息
            $(".customer-account-div img").attr('src',user_info.avatar);
            $(".customer-account-username").html(user_info.nickname);
            $(".customer-account-mobile").html(user_info.mobile);
            $(".customer-account-info-money").html("余额:"+user_info.money);
            $(".customer-account-info-score").html("积分:"+user_info.score);
            $(".customer-info-detail-div-title span").text(user_info.groupname);

            //默认加载用户优惠券
            $.ajax({
                type: 'POST',
                url: '/cashdesk/index/getcoupons',
                dataType: "json",
                data: {userid:user_id},
                success: function (ret) {
                    if (ret.code != 1) {
                        layer.open({
                            type: 1,
                            title:'提示',
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">获取失败</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                layer.close(index); // 关闭弹窗
                            }
                        });
                        return false;
                    }else{
                        var coupons_list = ret.data;
                        var coupons_html = '';
                        $(".coupon_list").html("");
                        if(coupons_list.length != 0){
                            for (var key in coupons_list) {
                                if(orderinfo['coupon'] && coupons_list[key]['id'] == orderinfo['coupon']['coupon_id']){
                                    coupons_html += '<div class="col-xs-5 coupon_list_item coupon_list_item_active" data-couponid="'+coupons_list[key]['id']+'" data-couponprice="'+coupons_list[key]['price']+'" data-coupontype="'+coupons_list[key]['usertype']+'" data-coupondiscount="'+coupons_list[key]['coupondiscount']+'" data-couponlimit="'+coupons_list[key]['limit']+'">';
                                }else{
                                    coupons_html += '<div class="col-xs-5 coupon_list_item" data-couponid="'+coupons_list[key]['id']+'" data-couponprice="'+coupons_list[key]['price']+'" data-coupontype="'+coupons_list[key]['usertype']+'" data-coupondiscount="'+coupons_list[key]['coupondiscount']+'" data-couponlimit="'+coupons_list[key]['limit']+'">';
                                }
                                coupons_html += '<div class="coupon_list_item_detail">';
                                coupons_html += '<img src="/assets/cashdesk/img/enable_coupon_icon.svg" alt="">';
                                if(coupons_list[key]['usertype'] == 'reduction'){
                                    coupons_html += '<span>'+coupons_list[key]['price']+'元优惠券</span></div>';
                                }else{
                                    coupons_html += '<span>'+coupons_list[key]['discount']*100+'折优惠券</span></div>';
                                }
                                
                                coupons_html += '<div class="coupon_list_item_div"><span>可用</span></div></div>';
                            }
                        }

                        if(coupons_html != ''){
                            $(".coupon_list").html(coupons_html);
                            coupons_html = '';
                        }
                    }
                },
                error: function (ret) {
                    layer.open({
                        type: 1, 
                        area: ['280px', '180px'],
                        title:'提示',
                        content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                        btn: ['确定'], // 弹窗按钮
                        btnAlign:"c",
                        yes: function(index, layero){
                            // 点击确定按钮后的回调函数
                            // index是弹窗的索引，layero是弹窗的DOM对象
                            layer.close(index); // 关闭弹窗
                        }
                    });
                }
            });

            //默认加载用户卡项
            $.ajax({
                type: 'POST',
                url: '/cashdesk/index/getuserordercards',
                dataType: "json",
                data: {userid:user_id},
                success: function (ret) {
                    if (ret.code != 1) {
                        layer.open({
                            type: 1,
                            title:'提示',
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">获取失败</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                layer.close(index); // 关闭弹窗
                            }
                        });
                        return false;
                    }else{
                        var coupons_list = ret.data;
                        var coupons_html = '';
                        $(".card-coupon-list").html("");
                        if(coupons_list.length != 0){

                            for (var key in coupons_list) {
                                var spent_money = parseFloat(parseFloat(coupons_list[key]['spent']) + parseFloat(coupons_list[key]['gift'])).toFixed(2);
                                if(orderinfo['cardcoupon'] && Object.keys(orderinfo['cardcoupon']).length != 0 && orderinfo['cardcoupon']['card_id'] && coupons_list[key]['id'] == orderinfo['cardcoupon']['card_id']){
                                    coupons_html += '<div class="card-coupon-item-div coupon_active" data-cardid="'+coupons_list[key]['id']+'" data-cardprice="'+spent_money+'">';
                                }else{
                                    coupons_html += '<div class="card-coupon-item-div " data-cardid="'+coupons_list[key]['id']+'" data-cardprice="'+spent_money+'">';
                                }
                                coupons_html += '<div class="card-coupon-item-info">';
                                coupons_html += '<div>';
                                coupons_html += '<div class="card-coupon-item-info-name">'+coupons_list[key]['name']+'</div>';
                                coupons_html += '<div class="card-coupon-item-info-content"></div>';
                                coupons_html += '</div>';
                                
                                coupons_html += '<div class="card-coupon-item-info-price">￥'+spent_money+'</div>';
                                coupons_html += '</div>';
                                coupons_html += '<div class="card-coupon-item-lifespan">';
                                coupons_html += '<div class="card-coupon-item-lifespan-expiration">有效期: '+coupons_list[key]['time']+'</div>';
                                coupons_html += '<div class="card-coupon-item-lifespan-times"></div>';
                                coupons_html += '</div>';
                                coupons_html += '<div class="card-coupon-item-detail">';
                                coupons_html += '<div class="card-coupon-item-detail-title">'+coupons_list[key]['type_name']+'</div>';
                                coupons_html += '<div class="col-sm-8" style="text-align:right;">';
                                coupons_html += '<span>有效期至：'+coupons_list[key]['time']+'</span>';
                                coupons_html += '</div>';
                                coupons_html += '</div>';
                                coupons_html += '</div>';
                            }
                        }

                        if(coupons_html != ''){
                            $(".card-coupon-list").html(coupons_html);
                            coupons_html = '';
                        }
                    }
                },
                error: function (ret) {
                    layer.open({
                        type: 1, 
                        area: ['280px', '180px'],
                        title:'提示',
                        content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                        btn: ['确定'], // 弹窗按钮
                        btnAlign:"c",
                        yes: function(index, layero){
                            // 点击确定按钮后的回调函数
                            // index是弹窗的索引，layero是弹窗的DOM对象
                            layer.close(index); // 关闭弹窗
                        }
                    });
                }
            });

            //加载支付信息
            $.ajax({
                type: 'POST',
                url: '/cashdesk/index/getpayways',
                dataType: "json",
                data: {userid:user_id},
                success: function (ret) {
                    if (ret.code != 1) {
                        layer.open({
                            type: 1,
                            title:'提示',
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">获取失败</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                layer.close(index); // 关闭弹窗
                            }
                        });
                        return false;
                    }else{
                        var ways_list = ret.data;
                        var pay_way_html = '';
                        $(".payment-list").html("");
                        if(ways_list.length != 0){
                            for (var key in ways_list) {
                                    pay_way_html += '<div class="payment-main">';
                                    pay_way_html += '<div class="payment-item-type">';
                                    pay_way_html += '<img class="payment-img" src="'+ways_list[key]['img']+'">';
                                    pay_way_html += '<div class="payment-name">'+ways_list[key]['name']+'</div>';
                                    pay_way_html += '</div>';
                                    pay_way_html += '</div>';
                                    pay_way_html += '<div class="payment-sub">';
                                    var sub_list = ways_list[key]['sublist'];
                                    for (var key1 in sub_list) {
                                        pay_way_html += '<div class="payment-item" data-id="'+sub_list[key1]['id']+'" data-ptype="'+sub_list[key1]['type']+'">';
                                        pay_way_html += '<img class="payment-img" src="'+sub_list[key1]['icon']+'">';
                                        pay_way_html += '<div class="payment-name">'+sub_list[key1]['name']+'</div>';
                                        pay_way_html += '</div>';
                                    }
                                    pay_way_html += '</div>';
                                    pay_way_html += '<div class="payment-row"></div>';
                            }
                        }

                        if(pay_way_html != ''){
                            $(".payment-list").append(pay_way_html);
                            pay_way_html = '';
                            if (payinfo){
                                $.each(payinfo, function (index, item) {
                                    if (item.type == 2) {
                                        $('.payment-item[data-ptype=2]').hide();
                                    }else{
                                        $('.payment-item[data-id='+item.id+']').hide();
                                    }
                                });
                            }else{
                                $('.payment-item').show();
                            }
                        }
                    }
                },
                error: function (ret) {
                    layer.open({
                        type: 1, 
                        area: ['280px', '180px'],
                        title:'提示',
                        content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                        btn: ['确定'], // 弹窗按钮
                        btnAlign:"c",
                        yes: function(index, layero){
                            // 点击确定按钮后的回调函数
                            // index是弹窗的索引，layero是弹窗的DOM对象
                            layer.close(index); // 关闭弹窗
                        }
                    });
                }
            });

            //加载订单支付数据
            $('.payment-resultant').html("");
            if (payinfo){
                $('.payment-resultant').html("");
                $.each(payinfo, function (index, item) {
                    let add_html = '';
                    add_html += '<div class="resultant-item" data-id="'+item.id+'" data-ptype="'+item.type+'">';
                    add_html += '<img class="resultant-img" src="'+item.img+'">';
                    add_html += '<span class="method-name">'+item.name+'</span>';
                    add_html += '<input type="number" step="0.01" min="0.00" class="pay_amount" placeholder="0.00" value="'+item.amount+'" />';
                    add_html += '<a href="javascript:void(0);" class="link get-all-amount">全额</a>';
                    add_html += '<a href="javascript:void(0);" class="link get-difference-amount">差额</a>';
                    add_html += '<span class="close close-item">×</span>';
                    add_html += '</div>';
                    if (item.type == 2) {
                        $('.pay-order-div').show();
                        if (item.id == 10) {
                            $('.qrcode-pay-item').show();
                            if (orderinfo['qrcode_img']) {
                                $(".pay_qrcode").attr("src",orderinfo['qrcode_img'])
                            }
                            $('.scan-pay-item').hide();
                        }else if(item.id == 12){
                            $('.qrcode-pay-item').hide();
                            $('.scan-pay-item').show();
                        }
                    }
                    $('.payment-resultant').append(add_html);
                });
            }

            if (typeof orderinfo['order_id'] != 'undefined') {
                $('.pay_item_btn').attr('disabled',true);
            }

            //加载已选择的销售人员信息
            if(orderinfo){
                //加载订单统计信息
                $(".total_fee").text('￥'+orderinfo['originalfee']);
                $(".modify_fee").text('￥'+orderinfo['modifyfee']);
                $(".card_discount_fee").text('-￥'+orderinfo['discountfee']);
                $('.uprice_fee').text('-￥'+orderinfo['upricefee']);
                $(".card_discount").text('-￥'+orderinfo['carddiscount']);
                $(".discount_fee").text('-￥'+orderinfo['vipdiscount']);
                $(".coupon_fee").text('-￥'+orderinfo['discount']);

                var actual_amount = 0;
                if (orderinfo['modifyfee'] != 0) {
                    actual_amount = orderinfo['modifyfee'] - orderinfo['discount'] - orderinfo['discountfee'] - orderinfo['carddiscount'] - orderinfo['vipdiscount'];
                }else{
                    actual_amount = orderinfo['totalfee'] - orderinfo['discount'] - orderinfo['discountfee'] - orderinfo['carddiscount'] - orderinfo['vipdiscount'];
                }
                if (actual_amount < 0 ) {
                    actual_amount = 0;
                }
                actual_amount = parseFloat(actual_amount).toFixed(2);
                var user_money = parseFloat(user_info.money).toFixed(2);
                $(".total_cost_fee").text('￥'+actual_amount);
                $(".actual_amount").text(actual_amount);
                $(".actual_amount").data('amount',actual_amount);

                //处理赠送项目
                if(orderinfo['giftdata'] && orderinfo['giftdata'].length > 0){
                    var giftdata = orderinfo['giftdata'];
                    var gift_html = '<table class="gridtable">';
                    gift_html += '<th style="width:40%;">赠送项目</th>';
                    gift_html += '<th style="width:10%;">原价</th>';
                    gift_html += '<th style="width:10%;">数量</th>';
                    gift_html += '<th>有效期至</th>';

                    $.each(giftdata, function (index, item) {
                        if (item.type == 1) {
                            item.goods_name += '(商品)';
                        }else if(item.type == 2){
                            item.goods_name += '(服务)';
                        }else{
                            item.goods_name += '(优惠券)';
                        }
                        gift_html += '<tr>';
                        gift_html += '<td>'+item.goods_name+'</td>';
                        gift_html += '<td>￥'+item.price+'</td>';
                        gift_html += '<td>'+item.number+'</td>';
                        if (item.type == 2) {
                            var validtime = ''
                            if (typeof item.validtime != 'undefined') {
                                validtime = item.validtime
                            }
                            
                            gift_html += '<td><input type="text" class="form-control validtime" placeholder="请选择有效期" data-id="'+item.itemid+'" id="validtime'+item.itemid+'" value="'+validtime+'"></td>';
                        }else{
                            gift_html += '<td>-</td>';
                        }
                        gift_html += '</tr>';
                    });

                    gift_html += '</table>';
                    $('.gift-list').html('');
                    $('.gift-list').append(gift_html);

                    initDatePickers(countkey,orderinfo);
                }
            }

            updatePaymentAmount();
        }
    }

    //生成支付二维码
    function createQrcode(params){
        $(".pay_qrcode").prop("src", "/cashdesk/index/build?"+objectToQueryString(params));
    }

    function initDatePickers(countkey,orderinfo) {
        var dateoobj = $('.validtime');
        dateoobj.each(function(index, element) {
            var ele_id = "#"+$(this).attr('id');
            var data_id = $(this).data('id');
            laydate.render({
                elem: ele_id,
                type:'datetime',
                change: function(value, date, endDate) {
                    if(orderinfo['giftdata'] && orderinfo['giftdata'].length > 0){
                        var giftdata = orderinfo['giftdata'];
                        $.each(giftdata, function (index, item) {
                            if (item.itemid == data_id) {
                                item.validtime = value;
                            }
                        })
                        var serializedArray = JSON.stringify(orderinfo);
                        sessionStorage.setItem(countkey, serializedArray);
                    }
                }
            });
        });
    }

    function clearSession(data_type,is_all=1){
        var customerinfo = sessionStorage.getItem('customer');
        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;

            if (is_all == 1) {
                //清除客户信息
                sessionStorage.removeItem('customer');
            }
            //清除支付信息
            sessionStorage.removeItem(data_type+'orderpay_'+user_id);

            if (data_type == 'cards') {
            //清除用户订单信息
                var goodsorder = sessionStorage.getItem('cardsorder_'+user_id);
                if (goodsorder && goodsorder.length != 0) {
                    sessionStorage.removeItem('cardsorder_'+user_id);
                }

                //清除用户订单统计信息
                var goodsordercount = sessionStorage.getItem('cardsordercount_'+user_id);
                if (goodsordercount && goodsordercount.length != 0) {
                    sessionStorage.removeItem('cardsordercount_'+user_id);
                }
            }else{
                //清除用户订单信息
                var goodsorder = sessionStorage.getItem('goodsorder_'+user_id);
                if (goodsorder && goodsorder.length != 0) {
                    sessionStorage.removeItem('goodsorder_'+user_id);
                }

                //清除用户订单统计信息
                var goodsordercount = sessionStorage.getItem('goodsordercount_'+user_id);
                if (goodsordercount && goodsordercount.length != 0) {
                    sessionStorage.removeItem('goodsordercount_'+user_id);
                }
            }
        }
    }

    //计算支付金额
    function updatePaymentAmount(){
        let data_type = 'goods';
        var currentkey = sessionStorage.getItem('currentkey');
        let user_id = 0;

        if (currentkey) {
            var current_key = JSON.parse(currentkey);
            data_type = current_key['datatype'];
        }

        var customerinfo = sessionStorage.getItem('customer');
        if(customerinfo && customerinfo.length != 0){
            user_id = user_info.id;
        }else{
            window.location = '/cashdesk';
        }

        var paykey = data_type+'orderpay_'+user_id;

        //需要支付的总金额
        let actual_amount = $('.actual_amount').data('amount');
        let pay_item_obj = $('.pay_amount');
        let total_amount = 0;
        let pay_list = [];
        pay_item_obj.each(function(index, element) {
            let pay_way_id = $(element).closest('.resultant-item').data('id');
            let amount = parseFloat($(element).val()) || 0;
            let curamount = amount.toFixed(2);
            let pay_img = $(this).parent('.resultant-item').find('.resultant-img').attr('src');
            let pay_name = $(this).parent('.resultant-item').find('.method-name').text();
            let pay_type = $(this).parent('.resultant-item').data('ptype');
            if (pay_type == 2) {
                $(".order-detail-total-fee").text(curamount);
            }
            total_amount += amount;
            let pay_detail = {
                id: pay_way_id,
                img: pay_img,
                type: pay_type,
                name: pay_name,
                amount: curamount
            };
            pay_list.push(pay_detail);
        });

        let difference_amount = parseFloat(actual_amount - total_amount).toFixed(2);

        $('.actual_amount').text(difference_amount);

        var serializedArray = JSON.stringify(pay_list);
        sessionStorage.setItem(paykey, serializedArray);
    }
});
